import os
import sys
import pandas as pd
import datetime
from MainConsolidator import MainConsolidator

class handler(object):
    @staticmethod
    def module_name():
        return 'Труба бесшовная ТПЦ'
    @staticmethod
    def handle(row:pd.Series,consolidator:MainConsolidator)->pd.Series:
        product_up=None
        try:
            product = row["Первичный продукт"]
            thickness = row["Толщина стенки, мм <Производство>"]
            diametr = row["Диаметр, мм <Производство>"]
            vm_code = row['Вид материала в SAP ERP'][:4]
            steel_mark = row["Марка стали <Производство>"]
            
            pipe_type = consolidator.scalar_in_guid("Виды материалов ТПЦ",f"`Код`=='{vm_code}'","Тип трубы")
            diametr_led = consolidator.nearest_in_guid("Параметры по Продукту ТПЦ",f"`Производство`=='Труба бесшовная ТПЦ'","Диаметр",diametr,"Диаметр")
            diametr_led_s = str(diametr_led).replace(".0","")
            thickness_range = consolidator.scalar_in_guid("Параметры по Продукту ТПЦ",f"`Производство`=='Труба бесшовная ТПЦ' and `Мин`<={thickness}<=`Макс`","Диапазон")
            gmsps = consolidator.get_gmsps(steel_mark,product)
            # if pd.isna(gmsps): gmsps = f"[{steel_mark}]" # for debug
            print(f"{product}: {thickness}: {diametr} -> {diametr_led_s}: {pipe_type}")
            product_up = f"{product} Д{diametr_led_s} {thickness_range} {gmsps}"
            if "ИВ" in pipe_type: product_up = f"{product_up} ИВ"
            row["error"] = pd.NA
        except Exception as exp: 
            row["error"] = f"{exp}"
        finally:
            row["Продукт УП"]=product_up
            row["Время укрупнения"]=datetime.datetime.now()
            return row
        
    def debug_handle(self,inputDf:pd.DataFrame,consolidator:MainConsolidator,module:str=None)->pd.DataFrame:
        try:
            if module is None: return inputDf.apply(lambda row: self.handle(row,consolidator), axis=1)
            else: return inputDf[inputDf["Производство2"]==module].apply(lambda row: self.handle(row,consolidator), axis=1)
        except: raise
    
    def get_compiled(self):
        code:str=f"print('{__file__}')"
        try:
            with open(__file__,encoding="utf-8",mode="r") as f:
                code=f.read()
        except Exception as exp: 
            code=f"print('error: {exp}')"
        finally:
            cc = compile(code,"","exec")
            return cc

if __name__=="__pipe_tpc__":
    consolidator:MainConsolidator
    record:pd.Series
    result:pd.Series
    result = handler.handle(record,consolidator)

